package com.example.onlinemarket.activity;

import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import com.example.onlinemarket.R;
import com.example.onlinemarket.adapter.RecyclerViewAdapter;
import com.example.onlinemarket.model.MobileOrderItem;
import com.example.onlinemarket.model.OrderInfo;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.onlinemarket.Application.dismissProgressDialog;
import static com.example.onlinemarket.Application.loginUser;
import static com.example.onlinemarket.Application.showProgressDialog;
import static com.example.onlinemarket.util.ActivityUtil.goShop;
import static com.example.onlinemarket.util.ActivityUtil.jumpToActivityForResult;
import static com.example.onlinemarket.util.HttpUtil.sendHttpRequest;
import static com.example.onlinemarket.util.JSONUtil.fromJsons;
import static com.example.onlinemarket.util.JSONUtil.toJsonWithAnnotation;

public class OrderActivity extends BaseActivity {

    //订单状态
    public static final int UNSENT_STATUS = 0;
    public static final int SENT_STATUS = 1;
    public static final int SIGNED_STATUS = 2;
    public static final int REFUNDING_STATUS = 3;
    public static final int REFUND_STATUS = 4;
    public static final int CONFIRM_STATUS = 5;
    private int status = 0;

    private TabLayout tabs;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private LinearLayout tipLayout;
    private RecyclerViewAdapter<OrderInfo> adapter;

    private List<OrderInfo> orderInfoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        //初始化组件
        initWidgets();
        //初始化数据
        initData();
        //设置事件监听器
        setWidgetsListener();
        dismissProgressDialog();
    }

    //初始化数据
    private void initData() {
        //根据想跳转到的页面获取订单数据
        status = getIntent().getIntExtra("status", 0);
        switchTab(status);
    }

    //初始化组件
    private void initWidgets() {
        tabs = findViewById(R.id.tabs_order);
        refreshLayout = findViewById(R.id.layout_refresh);
        tipLayout = findViewById(R.id.order_tip);
        recyclerView = findViewById(R.id.order_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    //设置事件监听器
    private void setWidgetsListener(){
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int pos = tabs.getSelectedTabPosition();
                if(status!=pos)
                    switchTab(pos);
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            switchTab(status);
            refreshLayout.finishRefresh(true);
        });
        // TODO: 2021/6/16
//        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                refreshLayout.finishRefresh(true);
//            }
//        });
    }

    private void switchTab(int status){
        tabs.selectTab(tabs.getTabAt(status));
        this.status = status;
        showProgressDialog(this);
        new Thread(() -> {
            String orderStatus = "";
            switch (status){
                case UNSENT_STATUS:
                    orderStatus = "待发货";
                    break;
                case SENT_STATUS:
                    orderStatus = "已发货";
                    break;
                case SIGNED_STATUS:
                    orderStatus = "已签收";
                    break;
                case REFUNDING_STATUS:
                    orderStatus = "%退款中";
                    break;
                case REFUND_STATUS:
                    orderStatus = "已退款";
                    break;
                case CONFIRM_STATUS:
                    orderStatus = "已确认";
                    break;
                default:
                    break;
            }
            Map<String, String> map = new HashMap<>();
            map.put("userId", String.valueOf(loginUser.getUserId()));
            map.put("orderStatus", orderStatus);
            String responseData = sendHttpRequest("/order", "POST", map);
            if(responseData!=null&&!responseData.isEmpty()){
                orderInfoList = fromJsons(responseData, new TypeToken<List<OrderInfo>>() {}.getType());
                if(orderInfoList!=null&&orderInfoList.size()>0){
                    new Thread(() -> {
                        for(OrderInfo info:orderInfoList)
                            for(MobileOrderItem orderItem:info.orderItemList)
                               orderItem.getGoodImg();
                        runOnUiThread(this::resetAdapter);
                    }).start();
                }else
                    runOnUiThread(() -> {
                        showTip();
                        dismissProgressDialog();
                    });
            }else
                runOnUiThread(() -> {
                    showTip();
                    dismissProgressDialog();
                });
        }).start();
    }

    //重置视图
    @UiThread
    private void resetUi(){
        if(orderInfoList!=null&&orderInfoList.size()>0)
            resetAdapter();
        else{
            adapter = null;
            showTip();
        }
    }

    //重置适配器，刷新视图
    @UiThread
    private void resetAdapter(){
        adapter = getOrderAdapter();
        recyclerView.setAdapter(adapter);
        hideTip();
        dismissProgressDialog();
    }

    //显示无订单提示，隐藏RecyclerView
    private void showTip(){
        tipLayout.setVisibility(View.VISIBLE);
        refreshLayout.setVisibility(View.GONE);
    }

    //隐藏提示，显示RecyclerView
    private void hideTip(){
        tipLayout.setVisibility(View.GONE);
        refreshLayout.setVisibility(View.VISIBLE);
    }

    private RecyclerViewAdapter<OrderInfo> getOrderAdapter(){
        return new RecyclerViewAdapter<OrderInfo>(this, R.layout.order_item, orderInfoList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.order_item;
            }
            @Override
            public void convert(ViewHolder holder, OrderInfo data, int position) {
                holder.setText(R.id.tv_order_shop_name, data.order.getShopName());
                RecyclerView recyclerView = holder.itemView.findViewById(R.id.recycler_view);
                recyclerView.setLayoutManager(new LinearLayoutManager(OrderActivity.this));
                recyclerView.setAdapter(getOrderInfoAdapter(data.orderItemList));
                holder.setOnClickListener(R.id.tv_order_shop_name, v -> new Thread(() -> goShop(OrderActivity.this, data.order.getShopId())).start());
                double totalPrice = 0;
                for(MobileOrderItem item:data.orderItemList){
                    totalPrice += item.sellPrice*item.goodNum;
                }
                String totalPriceText = "总价：￥"+totalPrice;
                holder.setText(R.id.tv_order_total_price, totalPriceText);
            }
        };
    }

    private RecyclerViewAdapter<MobileOrderItem> getOrderInfoAdapter(List<MobileOrderItem> orderItemList){
        return new RecyclerViewAdapter<MobileOrderItem>(this, R.layout.order_item_item, orderItemList) {
            @Override
            public int getLayoutId(int viewType) { return R.layout.order_item_item; }
            @Override
            public void convert(ViewHolder holder, MobileOrderItem data, int position) {
                holder.setText(R.id.iv_order_item_item_good_id, String.valueOf(data.goodId));
                holder.setText(R.id.tv_order_item_item_good_name, data.goodName);
                holder.setImage(R.id.iv_order_item_item_good_img, data.imgPath);
                String priceText = "￥"+data.sellPrice;
                holder.setText(R.id.tv_order_item_item_good_price, priceText);
                String numText = "x"+data.goodNum;
                holder.setText(R.id.tv_order_item_item_good_num, numText);
                String totalPriceText = "总计：￥"+(data.sellPrice*data.goodNum);
                holder.setText(R.id.tv_order_item_item_total_price, totalPriceText);
                holder.setOnClickListener(R.id.layout_order_item, v -> {
                    showProgressDialog(OrderActivity.this);
                    new Thread(() -> {
                        OrderInfo goalOrder = null;
                        for(OrderInfo info:orderInfoList){
                            if(info.orderItemList.get(0).orderId==data.orderId){
                                goalOrder = info;
                                break;
                            }
                        }
                        if(goalOrder!=null){
                            Map<String, String> map = new HashMap<>();
                            map.put("status", String.valueOf(status));
                            map.put("order", toJsonWithAnnotation(goalOrder, OrderInfo.class));
                            map.put("date", String.valueOf(goalOrder.order.getTime().getTime()));
                            jumpToActivityForResult(OrderInfoActivity.class, map, 0);
                        }
                    }).start();
                });
            }
        };
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK&&requestCode==0){
            new Thread(() -> {
                if(data!=null){
                    int orderId = data.getIntExtra("orderId", -1);
                    if(orderId!=-1){
                        int i;
                        for(i=0;i<orderInfoList.size();i++)
                            if(orderInfoList.get(i).order.getOrderId()==orderId)
                                break;
                        if(i!=-1){
                            int finalI = i;
                            runOnUiThread(() -> {
                                orderInfoList.remove(finalI);
                                resetUi();
                            });
                        }
                    }
                }
            }).start();
        }
    }
}